class Solution(object):
    def nextClosestTime(self, time):
        """
        :type time: str
        :rtype: str
        """
        time_h, time_m = time.split(':')
        time_h = int(time_h)
        time_m = int(time_m)
        now_time = time_h * 60 + time_m
        self.diff = float('inf')
        self.time = None

        def cal_item(time1):
            time1_h, time1_m = time1.split(':')
            time1_h = int(time1_h)
            time1_m = int(time1_m)
            if 0 <= time1_h < 24 and 0 <= time1_m < 60:
                now_time1 = time1_h * 60 + time1_m
                if (now_time1 + 86400 - now_time) % 86400 < self.diff:
                    self.diff = (now_time1 + 86400 - now_time) % 86400
                    self.time = time1

        num = set()
        for i in range(5):
            if i != 2:
                num.add(time[i])
        num_list = []

        def search(i):
            if i == 4:
                time1 = num_list[0] + num_list[1] + ':' + num_list[2] + num_list[3]
                if time1 != time:
                    cal_item(time1)
            else:
                for item in num:
                    num_list.append(item)
                    search(i + 1)
                    num_list.pop()
        search(0)
        if not self.time:
            return time
        return self.time


data = Solution()
time = "00:00"
print(data.nextClosestTime(time))
